/*
 *                                                     __----~~~~~~~~~~~------___
 *                                    .  .   ~~//====......          __--~ ~~
 *                    -.            \_|//     |||\\  ~~~~~~::::... /~
 *                 ___-==_       _-~o~  \/    |||  \\            _/~~-
 *         __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
 *     _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
 *   .~       .~       |   \\ -_    /  /-   /   ||      \   /
 *  /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
 *  |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
 *           '         ~-|      /|    |-~\~~       __--~~
 *                       |-~~-_/ |    |   ~\_   _-~            /\
 *                            /  \     \__   \/~                \__
 *                        _--~ _/ | .-~~____--~-/                  ~~==.
 *                       ((->/~   '.|||' -_|    ~~-/ ,              . _||
 *                                  -_     ~\      ~~---l__i__i__i--~~_/
 *                                  _-~-__   ~)  \--______________--~~
 *                                //.-~~~-~_--~- |-------~~~~~~~~
 *                                       //.-~~~--\
 *                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * 
 *                               神兽保佑            永无BUG
 */

//由于深信服AC软件版本不同的原因，AC13.0.X和AC12.0.x部分功能并不相互适用
const _ = require('lodash')
const logger = require('./logs/logger')
const axios = require('axios')
const bodyParser = require('body-parser')
const express = require('express')
const md5 = require('md5')
const port = 5555
const app = express()
const fivePw = "password"
let count = 1


app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

//axios默认模板
axios.defaults.baseURL = 'http://www.baidu.com'
axios.defaults.headers.post['Content-Type'] = 'application/json';

app.post('/', async(req, res) => {
  console.log(req.body.data)
  let showGroup = await showGroupFuc(req.body.data)
  if(showGroup.data.message == '组不存在!' && req.body.data.type == 'add'){
    addGroupFuc(req.body.data)
  }else{
    if(req.body.data.type == 'add') {
      let tempData = randomFuc()
      addFuc(tempData,md5(fivePw + tempData),req.body.data)
    }else {
      let delData = randomFuc()
      delFuc(delData,md5(fivePw + delData),req.body.data)
    }
  }
  res.send('本地已接收到火星请求_5楼')
})
app.listen(port, () => {
  console.log(`深信服自动创建API接口启动,端口为${port}`)
})

//企业微信推送机器人

function rebot(allData) {
  axios.post('https://www.baidu.com', {
      "msgtype": "text",
      "text": {
          "content": `来自5楼深信服的消息:上网账号 ${allData.name} 创建失败，请尝试重新手动创建或者查看报错信息更正。`,
      }
  })
  .then((res) => {
    logger.info(res.data)
  })
  .catch((err) => {
    logger.info(err)
  })
}

//随机数方法
function randomFuc() {
  return _.random(1, 1000)
}


//添加用户
function addFuc(random,md5,data){
  axios.post('/user', 
  {
    "random": random.toString(),
    "md5": md5,
    "name": "ks" + data.number,
    "father_path": "/" + data.department, 
    "desc": data.name, 
    "show_name": data.name,
    "extend": {
      "self_pass": {
          "enable": true,
          "password": data.password,
          "modifyonce": true
      },
      "logout": true,
      "common_user": { 
        "enable": false,
        "allow_change": true
      },
  },
  
  })
  .then((res)=>{
    if(res.data.code !== 0){
      rebot(data)
    }
    logger.info(res.data)
  })
  .catch((err)=>{
    logger.info(err)
  })
}


//删除用户
function delFuc(random,md5,data){
  axios.post('/user?_method=DELETE', {
    "random": random.toString(),
    "md5": md5,
    "name": "ks" + data.number
  })
  .then((res)=>{
    logger.info(res.data)
  })
  .catch((err)=>{
    logger.info(err)
  })
}

//添加组
function addGroupFuc(data){
  let groupTemp = randomFuc().toString();
  axios.post('/group',
  {
    "random": groupTemp,
    "md5": md5(fivePw + groupTemp),
    "path": "/" + data.department,
  })
  .then((res)=>{
    if(res.data.code == 0){
      let tempData = randomFuc()
      addFuc(tempData,md5(fivePw + tempData),data)
    }
    logger.info(res.data)
  })
  .catch((err)=>{
    logger.info(err)
  })
}

//修改组信息(使用修改组信息来验证是否创建组)
function showGroupFuc(data){
    let groupTemp = randomFuc().toString();
    return axios.post('/group?_method=PUT',
    {
      "random": groupTemp,
      "md5": md5(fivePw + groupTemp),
      "path": "/" + data.department,
      "desc": (count++).toString()
    })
  }



// //修改组信息(异步调用测试)
// async function bb() {
//   let bbb = await showGroupFuc()
//   console.log(bbb.data)
// }

// bb()
